const USER_KEY = 'ZHONG__KE__USER__LOGIN'
const REMEMBER_LOGIN_USER = 'REMEMBER__LOGIN__USER'

export type TRememberUser = { password: string; username: string; isRemember: boolean }

function getStorage(key: string): false | Record<string, any> {
  const strVal = localStorage.getItem(key)
  if (strVal === null) {
    return false
  }
  try {
    const oVal = JSON.parse(strVal)
    return oVal
  } catch (e) {
    console.error('获取storage中用户信息失败', e)
    return false
  }
}

function setStorage(key: string, o: Record<string, any>) {
  localStorage.setItem(key, JSON.stringify(o))
}
function removeStorage(key: string) {
  localStorage.removeItem(key)
}

export function setUserInfo(oUser: IUser) {
  setStorage(USER_KEY, oUser)
}
export function removeUserInfo() {
  removeStorage(USER_KEY)
}
export function getUserInfo() {
  return getStorage(USER_KEY)
}
export function isAuthenticated(): boolean {
  const oUser = getUserInfo()
  return oUser === false ? false : !!(oUser.name && oUser.accessToken)
}

// remember user
export function setRememberUser(oUser: TRememberUser) {
  setStorage(REMEMBER_LOGIN_USER, oUser)
}
export function removeRememberUser() {
  removeStorage(REMEMBER_LOGIN_USER)
}
export function getRememberUser() {
  return getStorage(REMEMBER_LOGIN_USER)
}
